const io = require('../socket');

module.exports = {
  async getSocketByHotelId(hotelId) {
    const sockets = await io.in(hotelId).fetchSockets();
    if (sockets.length < 1) {
      throw new Error('Hotel local interface is offline.');
    } else {
      return sockets[0];
    }
  },

  /**
   * 调用远程 socket client
   * @param {*} socket 
   * @param {*} req 
   * @returns {Promise<unknown>}
   */
  remote(socket, req) {
    return new Promise((resolve, reject) => {
      if (!socket || typeof socket.emit !== 'function') {
        return reject(new Error('app error'));
      }

      socket.emit('call', req.method === 'GET' ? req.query : req.body, (data) => resolve(data));
    })
  }
}
